package indi.mozping.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author by mozping
 * @Classname Util
 * @Description TODO
 * @Date 2019/6/22 15:42
 */
public class SqlSessionFactoryUtil {

    private static volatile SqlSessionFactory factory;

    /**
     * 获取数据库SqlSessionFactory
     */
    public static SqlSessionFactory getSqlSessionFactoryInstace() {
        if (factory == null) {
            InputStream in = null;
            try {
                in = Resources.getResourceAsStream("foo/TestConfig.xml");
            } catch (Exception e) {
                e.printStackTrace();
            }
            synchronized (SqlSessionFactoryUtil.class) {
                if (factory == null) {
                    factory = new SqlSessionFactoryBuilder().build(in);
                }
            }
        }
        return factory;
    }

    /**
     * 根据指定配置文件获取数据库SqlSessionFactory
     */
    public static SqlSessionFactory getSqlSessionFactoryInstaceByConfig(String filePath) {
        if (factory == null) {
            synchronized (SqlSessionFactoryUtil.class) {
                if (factory == null) {
                    InputStream in = null;
                    try {
                        in = Resources.getResourceAsStream(filePath);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    factory = new SqlSessionFactoryBuilder().build(in);
                }
            }
        }
        return factory;
    }


    /**
     * 关闭SqlSession
     */
    public static void closeSession(SqlSession sqlSession) {
        if (sqlSession != null) {
            sqlSession.close();
        }
    }
}

